<template>
  <div class="verify-email-container">
    <el-card>
      <div v-if="loading">
        <div class="loading-content">
          <el-icon class="loading-icon"><Loading /></el-icon>
          <p>{{ $t('verifyEmail.loading') }}</p>
        </div>
      </div>
      <div v-else>
        <el-result
          :icon="success ? 'success' : 'error'"
          :title="success ? $t('verifyEmail.success') : $t('verifyEmail.failed')"
          :sub-title="message"
        >
          <template #extra>
            <div class="action-buttons">
              <el-button type="primary" @click="goLogin">{{ $t('verifyEmail.goLogin') }}</el-button>
              <el-button 
                v-if="!success" 
                type="warning" 
                @click="resendVerificationEmail"
                :loading="resendLoading"
                :disabled="resendCountdown > 0"
              >
                <span v-if="resendCountdown > 0">{{ $t('verifyEmail.resendCountdown', { countdown: resendCountdown }) }}</span>
                <span v-else>{{ $t('verifyEmail.resendEmail') }}</span>
              </el-button>
            </div>
          </template>
        </el-result>
      </div>
    </el-card>
  </div>
</template>

<script>
import { userApi } from '@/api';
export default {
  name: 'VerifyEmail',
  data() {
    return {
      loading: true,
      success: false,
      message: '',
      resendLoading: false,
      resendCountdown: 0,
      resendTimer: null,
      userEmail: ''
    };
  },
  async mounted() {
    const token = this.$route.query.token;
    console.log('邮箱激活页面加载，token:', token);
    
    if (!token) {
      this.loading = false;
      this.success = false;
      this.message = this.$t('verifyEmail.invalidToken');
      return;
    }
    
    try {
      // 调用后端验证接口
      console.log('开始验证邮箱，发送请求到:', `/verify-email?token=${token}`);
      const response = await userApi.verifyEmail(token);
      console.log('邮箱验证成功，响应:', response);
      
      this.success = true;
      // 使用后端返回的消息或默认消息
      this.message = response.data?.message || this.$t('verifyEmail.successMessage');
      
      // 如果后端返回了用户邮箱，保存用于重新发送
      if (response.data && response.data.email) {
        this.userEmail = response.data.email;
        console.log('获取到用户邮箱:', this.userEmail);
      }
      
    } catch (error) {
      console.error('邮箱验证失败:', error);
      this.success = false;
      
      // 根据不同的错误类型显示不同的提示信息
      if (error.response) {
        const status = error.response.status;
        const errorData = error.response.data;
        
        console.log('错误状态码:', status, '错误数据:', errorData);
        
        switch (status) {
          case 400:
            this.message = errorData.error || errorData.message || this.$t('verifyEmail.invalidToken');
            break;
          case 401:
            this.message = this.$t('verifyEmail.expiredToken');
            break;
          case 404:
            this.message = this.$t('verifyEmail.userNotFound');
            break;
          case 409:
            this.message = this.$t('verifyEmail.alreadyActivated');
            break;
          case 500:
            this.message = errorData.error || errorData.message || this.$t('verifyEmail.serverError');
            break;
          default:
            this.message = errorData.error || errorData.message || this.$t('verifyEmail.serverError');
        }
        
        // 如果错误响应中包含邮箱信息，保存用于重新发送
        if (errorData.email) {
          this.userEmail = errorData.email;
          console.log('从错误响应中获取到用户邮箱:', this.userEmail);
        }
      } else if (error.request) {
        this.message = '网络连接失败，请检查网络连接后重试。';
      } else {
        this.message = '激活过程中发生未知错误，请稍后重试。';
      }
    } finally {
      this.loading = false;
    }
  },
  beforeUnmount() {
    // 清理定时器
    if (this.resendTimer) {
      clearInterval(this.resendTimer);
      this.resendTimer = null;
    }
  },
  methods: {
    goLogin() {
      this.$router.push('/login');
    },
    
    async resendVerificationEmail() {
      if (this.resendCountdown > 0) return;
      
      // 如果没有邮箱信息，跳转到注册页面
      if (!this.userEmail) {
        this.$message.warning('无法获取邮箱信息，请返回注册页面重新注册。');
        this.$router.push('/register');
        return;
      }
      
      this.resendLoading = true;
      try {
        // 使用正确的接口调用
        const userType = localStorage.getItem('tempUserType') || 'student';
        const password = localStorage.getItem('tempUserPassword');
        const confirmPassword = localStorage.getItem('tempUserConfirmPassword');
        
        const response = await userApi.sendActivation({ 
          email: this.userEmail,
          userType: userType,
          password: password,
          confirmPassword: confirmPassword
        });
        
        this.$message.success('验证邮件已重新发送，请查收邮箱。');
        this.startResendCountdown();
      } catch (error) {
        let errorMessage = '重新发送验证邮件失败，请稍后重试。';
        
        if (error.response) {
          const { status, data } = error.response;
          switch (status) {
            case 400:
              errorMessage = data.error || data.message || '邮箱已验证或账户不存在';
              break;
            case 404:
              errorMessage = '邮箱不存在，请先注册';
              break;
            case 409:
            case 500:
              errorMessage = '该邮箱已被注册';
              break;
            case 429:
              errorMessage = '发送过于频繁，请稍后再试';
              break;
            default:
              errorMessage = data.error || data.message || errorMessage;
          }
        }
        
        this.$message.error(errorMessage);
      } finally {
        this.resendLoading = false;
      }
    },
    
    startResendCountdown() {
      this.resendCountdown = 60;
      this.resendTimer = setInterval(() => {
        this.resendCountdown--;
        if (this.resendCountdown <= 0) {
          this.clearResendCountdown();
        }
      }, 1000);
    },
    
    clearResendCountdown() {
      this.resendCountdown = 0;
      if (this.resendTimer) {
        clearInterval(this.resendTimer);
        this.resendTimer = null;
      }
    }
  }
};
</script>

<style scoped>
.verify-email-container {
  max-width: 500px;
  margin: 60px auto;
}

.loading-content {
  text-align: center;
  padding: 40px 0;
}

.loading-icon {
  font-size: 48px;
  color: #409eff;
  animation: rotate 2s linear infinite;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.loading-content p {
  margin-top: 20px;
  color: #606266;
  font-size: 16px;
}

.action-buttons {
  display: flex;
  gap: 12px;
  justify-content: center;
  flex-wrap: wrap;
}

.action-buttons .el-button {
  min-width: 120px;
}
</style> 